<!--待确认（终审结果）-->
<template>
  <div class="fianlJudment">
    <el-form :inline="true" :model="checkForm" label-width="100px" class="demo-ruleForm" ref="checkForm">

        <el-form-item label="审批金额" prop="approvalConclusionDTO.approveAmount" label-width="150px"  >
          <el-input disabled style="width: 300px;" type="number" v-model="checkForm.approvalConclusionDTO.approveAmount"><template slot="append">万</template></el-input>
        </el-form-item>
        <el-form-item label="抵押类型" prop="approvalConclusionDTO.pledgeType" label-width="150px" style="width: 50%;"
          >
          <DicSelect :disabledFlag="true" dictType = "抵押类型" :dictValue="checkForm.approvalConclusionDTO.pledgeType" v-on:dictValue="checkForm.approvalConclusionDTO.pledgeType = $event"/>
        </el-form-item>
        <el-form-item label="年限" prop="approvalConclusionDTO.loanTerm" label-width="150px"
          >
          <el-input disabled style="width: 300px;" type="number" v-model="checkForm.approvalConclusionDTO.loanTerm"><template slot="append">年</template></el-input>
        </el-form-item>
        <el-form-item label="资方" prop="approvalConclusionDTO.capitalSourceId" label-width="150px" style="width: 50%;"
          >
          <el-select
              style="min-width:100%;"
              v-model="checkForm.approvalConclusionDTO.capitalSourceId"
              @change="change"
              disabled
            >
              <el-option v-for="(item) in captialList" value-key="id" :key="item.id" :value="item.id" :label="item.capitalName"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="approvalConclusionDTO.capitalProductId" label-width="150px" 
          :rules="[{ required: false, message: '请选择产品', trigger: 'blur' }]">
          <!-- <el-input style="width: 300px;" disabled type="text" v-model="checkForm.approvalConclusionDTO.productName"></el-input> -->
           <el-select 
              style="min-width:100%;"
              v-model="checkForm.approvalConclusionDTO.capitalProductId" 
              @change="productChange"
              clearable
              disabled
            >
              <el-option v-for="(item) in productList" value-key="id" :key="item.id" :value="item.id" :label="item.productName"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="利率" prop="approvalConclusionDTO.annualInterestRate" label-width="150px" style="width: 50%;"
          >
          <el-input style="width: 300px;" disabled type="number" v-model="checkForm.approvalConclusionDTO.annualInterestRate"><template slot="append">%</template></el-input>
        </el-form-item>
        <el-form-item label="还款方式" prop="approvalConclusionDTO.repayMethod" label-width="150px" style="width: 450px;"
          >
          <DicSelect :disabledFlag="true" dictType = "还款方式" :dictValue="checkForm.approvalConclusionDTO.repayMethod" v-on:dictValue="checkForm.approvalConclusionDTO.repayMethod = $event"/>
        </el-form-item>
        <el-form-item label="抵押率" prop="approvalConclusionDTO.mortgageRate" label-width="150px" style="width: 50%;"
          >
          <el-input disabled style="width: 300px;" type="number" v-model="checkForm.approvalConclusionDTO.mortgageRate"><template slot="append">%</template></el-input>
        </el-form-item>
        <el-form-item label="带条件批复意见" prop="approvalConclusionDTO.approvalDesc" label-width="150px" style="width: 450px;"
          >
          <el-input disabled style="width: 300px;" type="textarea" v-model="checkForm.approvalConclusionDTO.approvalDesc"></el-input>
        </el-form-item>
        <el-form-item label="资料上传" prop="makeContractSignTime" label-width="150px" style="width: 50%;"
          >
           <el-button  type="primary" size="mini"
           @click="uploadFile()">上传文件</el-button>
           <el-button  type="primary" v-if="visbledLook()" size="mini" @click="lookFile()">查看文件</el-button>
        </el-form-item>
        <el-form-item label="批复时间" prop="approvalConclusionDTO.replyTime" label-width="150px"
          >

            <el-input disabled  style="width: 300px;" v-model="checkForm.approvalConclusionDTO.replyTime" />
        </el-form-item>
      <el-form-item  label-width="150px"  label=" ">
        <el-button type="primary" @click="updateData" v-loading="loading">保存</el-button>
      </el-form-item>
    </el-form>

     <!-- 添加或修改对话框 -->
    <el-dialog title="上传文件" :visible.sync="dialogFormVisible" :close-on-click-modal="false" >
      <el-form ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 90%; margin-left:50px;">

         <el-form-item label="文件列表" prop="fileUrlList">
           <!-- <el-upload
            :action="uploadPath"
            :file-list="galleryFileList"
            :headers="headers"
            :on-success="handleGalleryUrl"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            multiple
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card">
            <i  class="el-icon-plus"/>
            <div  slot="tip" class="el-upload__tip">只能上传.jpg,.jpeg,.png,.gif文件</div>
          </el-upload> -->
          <el-upload
          style="margin-top:30px;"
          class="upload-demo"
          drag
          :action="uploadPath"
          :file-list="galleryFileList"
          :headers="headers"
          :before-upload="handleBeforeUpload"
          :on-error="handleUploadError"
          :on-success="handleGalleryUrl"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-exceed="handleUploadLimit"
          accept=".jpg,.jpeg,.png,.gif,.pdf"
          multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
        </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small"  @click="dialogFormVisible = false">取消</el-button>
        <!-- <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button> -->
        <el-button type="primary" size="small" @click="dialogFormVisible = false">确定</el-button>
      </div>
    </el-dialog>


        <!-- 添加或修改对话框  v-if="dataForm.fileType === 12"-->
    <el-dialog title="查看文件" :visible.sync="dialogFormVisibleDetail" :close-on-click-modal="false" >
      <el-form ref="dataForm" :model="checkForm" status-icon label-position="left" label-width="100px" style="width: 80%; margin-left:50px;">

         <el-form-item label="缩略图" prop="approvalConclusionDTO.fileUrlList">
            <el-image
            draggable="true"
            class="list-item"
            v-for="(item) in checkForm.approvalConclusionDTO.fileUrlList"
            style="width: 100px; height: 100px"
            :src="item.fileUrl"
             fit="contain"
            v-if="handleShowFileType(item.fileUrl)"
             v-bind:key="item.id"
            :preview-src-list="previewPicUrlList">
          </el-image>
        </el-form-item>
        <el-form-item label="PDF" prop="fileUrlList">
           <div v-for="(item,index) in dataForm.fileUrlList" :key="index">
            <el-link v-if="!handleShowFileType(item.fileUrl)" type="primary" @click="handlePreviewPdf(item.fileUrl)">{{item.fileName}}</el-link>
           </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <!-- <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button> -->
        <el-button type="primary" size="small" @click="dialogFormVisibleDetail = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="预览" :visible.sync="dialogFormVisiblePic" :close-on-click-modal="false">
      <img  v-if="handleShowFileType(dialogImageUrl)" width="100%" :src="dialogImageUrl" alt="">
      <!-- <el-link v-else type="primary" @click="handlePreviewPdf(dialogImageUrl)">预览PDF</el-link> -->
      <!-- <iframe :src="dialogImageUrl"  width="100%" height="600px"></iframe> -->
    </el-dialog>
  </div>
</template>
<script>
import { toBeComfirmed,capitalDetail,finalReview,approvalDetail } from '@/api/project';
import { uploadPath,createApprovalFile } from '@/api/projectFile'
import DicSelect from '@/components/select'
import { getToken } from '@/utils/auth'
import {quertAllCapital,quertChoose} from "@/api/dashboard"
import { mapGetters } from 'vuex';
import pdf from 'vue-pdf'
export default {
   props: {
     projectId: undefined,
     taskId: undefined,
     itemActiveIndex:undefined
  },
  components: { DicSelect,pdf },
  data() {
    return {
      checkForm: {
        approveStatus: undefined,
        opinion: undefined,
       approvalConclusionDTO:{
          approveAmount: undefined,
          pledgeType:undefined,
          loanTerm: undefined,
          capitalSourceId: undefined,
          annualInterestRate: undefined,
          productName: undefined,
          approvalType:2,
          repayMethod: undefined,
          mortgageRate: undefined,
          approvalDesc: undefined,
          replyTime:undefined
        }
      },
      captialList: [],
      loading: false,
      dialogFormVisible:false,
      dialogFormVisibleDetail:false,
      dialogFormVisiblePic:false,
      dialogImageUrl:undefined,
      uploadPath,
      dataForm: {
        approvalConclusionId:undefined
      },
      galleryFileList:[],
      previewPicUrlList:[],
      productList:[],
      beforeArr: []
    };
  },
  computed: {
    ...mapGetters(['roles']),
    headers() {
      return {
        'Authorization': "Bearer-"+getToken()
      }
    }
  },
  created() {
    this.getCaptialList();
    this.approvalDetail();
  },
  methods: {
    visbledLook() {
      if(this.checkForm.approvalConclusionDTO.fileUrlList != undefined && this.checkForm.approvalConclusionDTO.fileUrlList.length > 0 ) {
        return true
      }
      return false
    },
    submitForm(checkForm) {
      this.$refs[checkForm].validate((valid) => {
          if (valid) {
            this.checkForm.projectId = this.projectId,
            this.checkForm.taskId = this.taskId,
            this.$confirm('你确定要提交吗?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }).then(() => {
              // 开始提交信息
              this.loading = true;
              finalReview(this.checkForm).then((data) => {
                this.loading = false;
                this.$message.success('操作成功');
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.go(-1);
              }).catch(() => {
                this.loading = false;
              })
            });
          } else {
            return false;
          }
        });
    },
    //节点判断
    handleChange(val) {
      this.restForm();
      this.checkForm.approveStatus = val;
      return;
    },
    handleShowFileType(item){
      if( item!=undefined &&  item.indexOf("pdf")==-1){
        return true
      }
      return false
    },
    restForm() {
      this.checkForm = {
        opinion: undefined,
        approvalConclusionDTO:{
          approveAmount: undefined,
          pledgeType:undefined,
          loanTerm: undefined,
          capitalSourceId: undefined,
          annualInterestRate: undefined,
          productName: undefined,
          approvalType:2,
          repayMethod: undefined,
          mortgageRate: undefined,
          approvalDesc: undefined,
          replyTime:undefined
        }
      };
    },
    getCaptialList() {
       quertAllCapital()
        .then(res => {
          this.captialList = res.data
        })
        .catch(() => {
          this.captialList = []
        })
    },
    change(e) {
     capitalDetail({capitalId: this.checkForm.approvalConclusionDTO.capitalSourceId})
        .then(res => {
          let pledgeType = this.checkForm.approvalConclusionDTO.pledgeType;
          this.checkForm.approvalConclusionDTO.productName = res.data.productName;
          this.checkForm.approvalConclusionDTO.annualInterestRate = pledgeType == 1 || pledgeType == 3 ? res.data.oneBetRate : res.data.twoBetRate;
        })
    },
    approvalDetail() {
      approvalDetail({approvalType:2,projectId:this.projectId})
        .then(res => {
          this.checkForm.approvalConclusionDTO = res.data;
          this.dataForm.approvalConclusionId = res.data.id
          this.dataForm.fileIdList = res.data.fileIdList
          this.dataForm.fileUrlList = res.data.fileUrlList
          quertChoose({capitalId: this.checkForm.approvalConclusionDTO.capitalSourceId,productType:1})
          .then(res => {
            this.productList = res.data
          })
          .catch(() => {
            this.productList = []
          })
        })
    },
     handleUploadError(res){
       this.$message({
        type: 'error',
        message: '上传文件失败'
      })
    },
    handleBeforeUpload(file){
      console.log(file)
      let beforeArrFlag = true
      this.beforeArr.forEach((item,index)=>{
        if( item.uid!=undefined && item.uid == file.uid) {
          beforeArrFlag = false
        }
      })
      if( beforeArrFlag ) {
      this.beforeArr.push(file)
      this.dataForm.fileUrlList.push(file)
      this.dataForm.fileIdList.push(file)
      }
    },
    handleGalleryUrl(response, file, fileList) {
      try{
      //  console.log(fileList)
       if(this.dataForm.fileUrlList === undefined){
        this.dataForm.fileUrlList = []
        this.dataForm.fileIdList = []
      }
      console.log(this.beforeArr)
      console.log(this.dataForm.fileUrlList)
      console.log("删除前")
      if (response.code === 20000) {
        for( let i=0 ; i< this.beforeArr.length; i++){
          if( this.beforeArr[i].uid == file.uid) {
            this.dataForm.fileUrlList.splice(i,1,{id:response.data.id,fileUrl:response.data.fileUrl,fileName:response.data.fileName})
            this.dataForm.fileIdList.splice(i,1,response.data.id)
          }
        }

      console.log(this.dataForm.fileUrlList)
      console.log("删除后")
      }
      }catch(error){
        this.$message.error(error)
      }finally{
      }
    },
    handleRemove: function(file, fileList) {
      try{
      console.log(this.dataForm.fileUrlList)
      for (var i = 0; i < this.dataForm.fileUrlList.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.fileUrl
        }

        if (this.dataForm.fileUrlList[i].fileUrl === url) {
          deleteProjectFile({fileId:this.dataForm.fileUrlList[i].id,fileType:this.dataForm.fileType,projectId:this.defaultProjectId})
            .then(() => {

            })
            .catch(response => {
            })
          this.dataForm.fileUrlList.splice(i, 1)
          this.dataForm.fileIdList.splice(i, 1)
          this.beforeArr.splice(i, 1)
        }
      }
      console.log(this.dataForm.fileUrlList)
      }catch(error){
        this.$message.error(error)
      }finally{

      }
    },
    handleUploadLimit(){
        this.$message.error("仅可以上传20个文件");
    },
    handlePictureCardPreview(file){
      console.log(file)
      if( file.response!=undefined){
        this.dialogImageUrl = file.response.data.fileUrl
      }else{
        this.dialogImageUrl = file.url
      }
      this.dialogFormVisiblePic = true
    },

    uploadFile() {
      // this.dataForm.picUrl = undefined
      this.beforeArr = []
      if( this.dataForm.fileUrlList!=undefined && this.dataForm.fileUrlList.length>0){
        this.beforeArr = Object.assign([],this.dataForm.fileUrlList)
      }
      if( this.dataForm.fileUrlList == undefined ) {
        this.dataForm.fileUrlList = []
        this.dataForm.fileIdList = []
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
       this.galleryFileList = []
        if( this.dataForm.fileUrlList!=undefined && this.dataForm.fileUrlList.length>0){
           for (var i = 0; i < this.dataForm.fileUrlList.length; i++) {
          this.galleryFileList.push({
            name: this.dataForm.fileUrlList[i].fileName,
            url: this.dataForm.fileUrlList[i].fileUrl
          })
        }
      }
    },
    lookFile() {
      // this.dataForm.picUrl = undefined
      //  this.galleryFileList = []
        if( this.dataForm.fileUrlList!=undefined && this.dataForm.fileUrlList.length>0){
           for (var i = 0; i < this.dataForm.fileUrlList.length; i++) {
          // this.galleryFileList.push({
          //   url: this.dataForm.fileUrlList[i].fileUrl
          // })
          if( this.dataForm.fileUrlList[i].fileName.indexOf("pdf")==-1){
          this.previewPicUrlList.push(this.dataForm.fileUrlList[i].fileUrl)
        }
        }
      }

      // this.picUrlList = row.fileUrlList
      this.dialogFormVisibleDetail = true
    },
    updateData() {
      console.log(this.dataForm)
      let flag = false
      if( this.dataForm.fileIdList == undefined || this.dataForm.fileIdList.length==0){
        flag = true
      }else{
      this.dataForm.fileIdList.forEach((item,index)=>{
        if( item==undefined) {
          flag = true
        }
      })
      }
      if( flag ) {
        this.$message.error("请稍等，您选择的文件还没有上传成功哦")
        return false
      }
      let data = {
        approvalConclusionId: this.dataForm.approvalConclusionId,
        fileIdList: this.dataForm.fileIdList
      }
      this.loading = true
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createApprovalFile(data)
            .then(() => {
              this.loading = false
              this.approvalDetail()
              this.$notify.success({
                title: '成功',
                message: '保存成功'
              })
            })
            .catch(response => {
            })
        }
      })
    },
  },

};
</script>

<style>
.fianlJudment .el-form-item__content{
  width:300px;
}
</style>
